<?php
class EJsonBehavior extends CBehavior{
	
	private $owner;
	private $relations;
	
	public function toJSON(){
		$this->owner = $this->getOwner();
		
		if (is_subclass_of($this->owner,'CActiveRecord')){
			
			$attributes       = $this->owner->getAttributes();
			$this->relations  = $this->getRelated();
			$attributes       = array_merge($attributes, $this->relations);
 
			return CJSON::encode($attributes);
		}
		return false;
	}
    
    
	private function getRelated($model = null)
	{	
		$related = array();
		$obj     = null;
        
		if(!$model) $model = $this->owner;
		$md = $model->getMetaData();
        
		foreach($md->relations as $name=>$relation){
			
			$obj = $model->getRelated($name);
			if(is_array($obj))
            {
                foreach($obj as $objInstance)
                {
                    $objAttrs     = $objInstance->getAttributes();
                    $objRelations = $this->getRelated($objInstance);
                    $objAttrs     = array_merge($objAttrs, $objRelations);
                    $related[$name][] = $objAttrs;
                }
            }
            else
            {
                $related[$name] = $obj->getAttributes() ;
            }
		}

	    return $related;
	}
}